select返回List
如果返回的是一个集合,那么resultType
应当为集合中元素的类型:
1
| public List<Employee> getEmpsByLastNameLike(String lastName);
|
1 2 3
| <select id="getEmpsByLastNameLike" resultType="com.glemontree.mybatis.bean.Employee"> select * from tbl_employee where last_name like #{lastName} </select>
|
select返回记录封装成map
返回一条记录的map,key就是列名,值就是对应的值:
1
| public Map<String, Object> getEmpByIdReturnMap(Integer id);
|
1 2 3
| <select id="getEmpByIdReturnMap" resultType="map"> select * from tbl_employee where id = #{id} </select>
|
1 2 3 4 5 6 7 8 9 10 11 12
| @Test public void test05() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try { EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); Map<String, Object> map = mapper.getEmpByIdReturnMap(1); System.out.println(map); } finally { openSession.close(); } }
|
最后的输出为:
1
| {gender=1, last_name=tom, id=1, email=tom@gmail.com}
|
多条记录封装一个map
Map<Integer, Employee>
:键是这条记录的主键,值是记录封装后的JavaBean
。
1 2
| @MapKey("id") public Map<Integer, Employee> getEmpByLastNameLikeReturnMap(String lastName);
|
1 2 3
| <select id="getEmpByLastNameLikeReturnMap" resultType="com.glemontree.mybatis.bean.Employee"> select * from tbl_employee where last_name like #{lastName} </select>
|
对于resultType属性,其实可以这样判断:我们查询出来的每条数据你希望是什么类型resultType就是什么类型,比如在上面一小节中返回一条记录的map,那么resultType就是map类型,而当多条记录封装一个map时,每条记录其实还是Employee,因此这里的resultType就是Employee。